


var job_id = Date.now();

var type="ozonNextQAjax";
chrome.runtime.sendMessage({ data: {type,job_id}, close: false });
console.log("ozonNextQAjax load");
chrome.runtime.onMessage.addListener(async (msg, sender) => {
  console.log(msg)
  setTimeout(() => {
     var msgObj = msg;
      console.log("job_id_info:"+msgObj.job_id+" --- " + job_id);
     if(msgObj.job_id !=job_id){

     }else{
        getByPage(msgObj,1,1);
     }

  }, 5000);

})

function getByPage(dataobj,try_time,page){
    console.log(dataobj);
    console.log("try_time:"+try_time);
    if(!dataobj.data.q){
        console.log("no q!! no data!!")
        return;
    }
    var url = "https://www.ozon.ru/search/?from_global=true&page="+page+"&text="+encodeURIComponent(dataobj.data.q);
    console.log("getByPage:"+url)
    var text = dataobj.data.q;
    var category = dataobj.data.cate;
    var get_max_page = dataobj.data.get_max_page
    var id = dataobj.data.id
    var sku_id = dataobj.data.sku_id
    $.ajax({
      url: url,
      method: 'GET',
      dataType: 'html',
      success: function(htmlContent) {
        // 将 HTML 页面内容解析为 DOM 元素
        const dom = $($.parseHTML(htmlContent));
        updateFirstPageByDom(dataobj,dom,text,category,get_max_page,sku_id,page);
      },
      error: function(xhr, status, error) {
        console.log('Ajax error: ', error);
        if (xhr.status === 403 && status === "error") {
            var type="ozonapi403";
            chrome.runtime.sendMessage({ data: {type}, close: false });
            console.log("遇到了403错误");
            startNextQ();
            //中断
        }else{
            setTimeout(() => {
                    getByPage(dataobj,try_time+1,page)
            },try_time * 20000);
        }
      }
    });
}



function startNextQ(){
    var type="ozonNextQAjax";
    chrome.runtime.sendMessage({ data: {type,job_id}, close: false });
}



function updateFirstPageByDom(dataobj,dom,text,category,get_max_page,sku_id,page){
    var noresult = false;
    var tf_state = "";
    var body = "";
    var itemCount = 0;
    var body={}
    dom.find('div[id^="state-searchResultsV2-"]').each(function() {
            var bodyDetail = $(this).attr("data-state");
            var data_state_obj = JSON.parse(bodyDetail);
            console.log(data_state_obj);
            itemCount = data_state_obj.items.length;
            body = bodyDetail;
    });

    var type="ozon_follow_search";
    var is_finish = 0;
    if(itemCount < 36){
        is_finish = 1;
    }

    var max_page = 10;
    if(dataobj.data.max_page){
        max_page = dataobj.data.max_page;
   }
    if(page >= max_page){
        is_finish = 1;
    }

    console.log("page_"+page+"_is_finish:"+is_finish);
    var type="search_follow_post";

    chrome.runtime.sendMessage({ data: {body,type,category,page,is_finish,text,sku_id}, close: false });
    if(is_finish== 1  || noresult==true){
        startNextQ();
    }else{
        getByPage(dataobj,1,page+1);
    }

}






